package cn.miju.wechatpay.handler;

import cn.miju.wechatpay.constant.WechatpayConstant;
import cn.miju.wechatpay.content.CodeMessage;
import cn.miju.wechatpay.properties.WechatpayProperties;
import cn.miju.wechatpay.request.WechatpayCloseOrderReq;
import cn.miju.wechatpay.response.WechatpayCloseOrderResp;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * <pre>
 * 业务类
 * </pre>
 *
 * @author Huzb
 * @version 1.0.0
 * @since 2023年05月04日 16:41
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatpayCloseOrderHandler extends AbstractWechatpayHandler<WechatpayCloseOrderReq, WechatpayCloseOrderResp> {

    /**
     * 请求参数前置处理
     *
     * @param req 请求参数
     * @return 结果
     */
    @Override
    protected String beforeRequest(WechatpayCloseOrderReq req) {
        WechatpayProperties wechatpayProperties = req.getWechatpayProperties();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mchid", wechatpayProperties.getMchId());
        return super.requsetAddOptParams(jsonObject, req.getOptionalParams());
    }

    /**
     * 核心执行
     *
     * @param req 请求参数
     * @return 结果
     */
    @Override
    public WechatpayCloseOrderResp doPlan(WechatpayCloseOrderReq req) {
        WechatpayProperties wechatpayProperties = req.getWechatpayProperties();
        CloseableHttpClient httpClient = super.getWechatpayClient(wechatpayProperties);
        String paramsStr = this.beforeRequest(req);
        String url = wechatpayProperties.getUrl() + String.format(WechatpayConstant.ApiUri.CLOSE, req.getOutTradeNo());
        HttpPost httpPost = super.getHttpPost(url, new StringEntity(paramsStr, StandardCharsets.UTF_8));

        CloseableHttpResponse response = null;
        WechatpayCloseOrderResp resp;

        // 发起请求
        try {
            try {
                log.info("API--关闭订单--【" + url + "】-->Request：{}", paramsStr);
                response = httpClient.execute(httpPost);
                String resultStr = EntityUtils.toString(response.getEntity());
                int statusCode = response.getStatusLine().getStatusCode();
                log.info("API--关闭订单--【" + url + "】-->httpCode:{} Response：{}", statusCode, resultStr);
                resp = this.afterResponse(resultStr, statusCode);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        } catch (IOException e) {
            log.error("API--关闭订单--【" + url + "】-->Exception：{}", e.getMessage(), e);
            return WechatpayCloseOrderResp.builder()
                    .code(CodeMessage.FAIL.getCode())
                    .msg(CodeMessage.FAIL.getMsg() + e.getMessage()).build();
        }

        return resp;
    }

    /**
     * 响应参数后置处理
     *
     * @param result     响应报文
     * @param statusCode 响应状态码
     * @return 结果
     */
    @Override
    protected WechatpayCloseOrderResp afterResponse(String result, int statusCode) {
        JSONObject jsonObject = JSON.parseObject(result);
        if (statusCode == SUCCESS_CODE_NO_RESPONSE) {
            return WechatpayCloseOrderResp.builder()
                    .code(CodeMessage.SUCCESS.getCode())
                    .msg(CodeMessage.SUCCESS.getMsg())
                    .build();
        } else {
            return WechatpayCloseOrderResp.builder()
                    .code(CodeMessage.FAIL.getCode())
                    .msg(CodeMessage.FAIL.getMsg() + "【" + jsonObject.get("code") + "】" + jsonObject.get("message"))
                    .build();
        }
    }
}
